import Layout from '@/layout' // 布局组件

export function getAsyncRoutes(routes) {
    const res = []
    // 定义路由中需要的自定名
    const keys = ['path', 'name', 'redirect', 'children', 'meta', 'hidden']
    // 遍历路由数组去重组可用的路由
    routes.forEach(item => {
        const newItem = {};
        const meta = {}
        if (item.component) {
            //判断 item.component 是否等于 'Layout',若是则直接替换成引入的 Layout 组件
            if (item.component === 'Layout') {
                newItem.component = Layout
            } else {
                //item.component 不等于 'Layout',则说明它是组件路径地址，因此直接替换成路由引入的方法
                newItem.component = resolve => require([`@/views/${item.component}`], resolve)
            }
        }
        for (const key in item) {
            if (keys.includes(key)) {
                newItem[key] = item[key]
            }
        }
        //若遍历的当前路由存在子路由，需要对子路由进行递归遍历
        if (newItem.children && newItem.children.length) {
            newItem.children = getAsyncRoutes(item.children)
        }
        res.push(newItem)
    })
    //返回处理好且可用的路由数组
    return res
}

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(routes) {
    const res = []
    routes.forEach(route => {
        const tmp = {
            ...route
        }
        // if (hasPermission(tmp)) {
        if (tmp.children) {
            tmp.children = filterAsyncRoutes(tmp.children)
        }
        res.push(tmp)
        // }
    })

    return res
}

const state = {
    routes: [],
    addRoutes: []
}

const mutations = {
    SET_ROUTES: (state, routes) => {
        // 这个地方维护了两个状态一个是addRouters，一个是routes
        state.routes = routes
    }
}

// 赋值菜单列表
const actions = {
    generateRoutes({
        commit
    }, menuList = []) {
        return new Promise(async (resolve) => {
            const asyncRoutes = getAsyncRoutes(menuList)
            asyncRoutes.push({
                path: '*',
                redirect: '/404',
                hidden: true
            })
            const accessedRoutes = filterAsyncRoutes(asyncRoutes)
            commit('SET_ROUTES', accessedRoutes)
            resolve(accessedRoutes)
        })
    }
}

export default {
    namespaced: true,
    state,
    mutations,
    actions
}